from django.shortcuts import render, redirect
from app02 import models
from app02.utils.pagination import Pagination
from django import forms
from app02.utils.form import UserModelForm
from app02.utils.bootstrap import BootStrapModelForm
from django.core.exceptions import ValidationError

from app02.utils.encrypt import md5


def admin_list(request):
    """ 管理员列表 """

    info_dict = request.session["info"]
    print(info_dict)

    queryset = models.adminis.objects.all()
    page_object = Pagination(request, queryset)

    context = {
        "admin_list": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 生成页码
    }

    return render(request, 'admin_list.html', context)


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=False)  # render_value=True 不清空，保留原来的值
    )

    class Meta:
        model = models.adminis
        fields = ["username", "password", "confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=False)  # render_value=True 不清空，保留原来的值
        }

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

    # 钩子方法
    def clean_confirm_password(self):
        """ 验证密码 self.cleaned_data """
        pwd = self.cleaned_data.get("password")
        confirm = md5(self.cleaned_data.get("confirm_password"))
        if confirm != pwd:
            raise ValidationError("密码不一致")

        # 返回什么，此字段以后保存到数据库就是什么
        return confirm


def admin_model_form_add(request):
    """ 添加管理员(ModelForm版本)"""
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, "admin_add.html", {"form": form})

    # 用户POST提交数据，数据校验
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)  {'username': '789', 'password': '456', 'confirm_password': '963'}
        form.save()
        return redirect("/admin/list/")
    else:
        return render(request, "admin_add.html", {"form": form})


def admin_edit(request, nid):
    row_objcet = models.adminis.objects.filter(id=nid).first()
    if request.method == "GET":
        form = AdminModelForm(instance=row_objcet)
        return render(request, 'admin_edit.html', {"form": form})
    # 保持到数据库
    form = AdminModelForm(data=request.POST, instance=row_objcet)
    if form.is_valid():
        form.save()
        return redirect("/admin/list/")
    else:
        # 校验失败(在页面上显示错误信息)
        return render(request, 'admin_edit.html', {"form": form})

def admin_delete(request,nid):
    """ 删除管理员"""
    models.adminis.objects.filter(id=nid).delete()
    return redirect("/admin/list/")